<template>
  <article>
    <div class="hander-com-table" style="padding: 10px 0">
      <slot name="header" />
      <slot />
    </div>
    <div>
      <div v-if="true" style="float: right">
        <table-setting
          :visible="tableSettingVisible"
          :columns="columnSetting"
          :table-name="tableName"
          @reload="setColumns"
          @close="closeTableSetting"
        />
      </div>
      <a-icon
        v-if="settings"
        type="setting"
        style="margin-bottom: 10px"
        theme="twoTone"
        @click="open"
      />
      <!-- <a-button
        v-if="settings"
        type="link"
        @click="open">
        设置
      </a-button> -->
      <a-table
        ref="table"
        :row-key="rowKey"
        :scroll="{ x, y }"
        :row-selection="rowSelection"
        :columns="tableColumns"
        :pagination="hasPage ? pagination : false"
        :data-source="url ? tableData : colData"
        :source-data="url ? tableData : colData"
        @change="handleTableChange"
      >
        <span
          v-for="item in columns"
          :key="item.key"
          :slot="item.key"
          slot-scope="text, record, $index"
        >
          <span v-if="!item.disabled">
            <span
              v-if="item.text"
              :disabled="
                item.setDisabled && item.setDisabled(record, item.text)
              "
              :style="{
                color: item.setColor ? item.setColor(text) : '#1989fa',
                cursor: 'pointer'
              }"
            >
              <!-- 操作按钮设置 -->
              <a-button
                v-if="typeof item.text === 'string'"
                type="link"
                :disabled="
                  item.setDisabled && item.setDisabled(record, item.text)
                "
                @click="doOperator(record, item.text, item.title, $index)"
                v-text="item.text"
              />
              <a-button
                v-for="i in item.text"
                v-else
                :key="i"
                :disabled="item.setDisabled && item.setDisabled(record, i)"
                type="link"
                style="margin-right: 6px"
                @click="doOperator(record, i, item.title, $index)"
                >{{ i }}</a-button
              >
            </span>

            <a-textarea
              v-if="item.operatorType === 'textarea'"
              v-model="record[item.key]"
              :disabled="item.disabled"
              :max="item.max || 100"
              :max-length="item.maxLength || 100"
              :placeholder="!item.disabled ? item.placeholder || '请输入' : ''"
              style="width: 85%"
              auto-size
              @change="
                e => {
                  changeInput(e, item.key, $index)
                }
              "
            />
            <a-input-number
              v-if="item.operatorType === 'inputNumber'"
              v-model="record[item.key]"
              style="width: 100%"
              :v="record[item.key] || ''"
              :min="'min' in item ? item.min : 1"
              :max="item.max || 100000000"
              :max-length="item.maxLength || 12"
              :step="item.step || 1"
              :placeholder="item.placeholder || '请输入'"
              :precision="item.precision === 0 ? 0 : item.precision || 1"
              :disabled="item.disabled"
              @blur="e => blurInput(e, item.key, $index)"
              @change="
                e => {
                  changeInput(e, item.key, $index)
                }
              "
            />

            <a-input
              v-if="item.operatorType === 'input'"
              v-model="record[item.key]"
              style="width: 100%"
              :placeholder="item.placeholder || '请输入'"
              :max-length="item.maxLength || 100"
              :disabled="item.disabled"
              @blur="e => blurInput(e, item.key, $index)"
              @change="
                e => {
                  changeInput(e, item.key, $index)
                }
              "
            />
            <a-auto-complete
              v-if="item.operatorType === 'autoComplate'"
              v-model="record[item.key]"
              :disabled="item.disabled"
              allow-clear
              :filter-option="filterOption"
              style="width: 100%"
              :data-source="
                record[item.key + 'List'] || item.selectOptions || []
              "
              placeholder="请输入"
              @blur="e => blurAutoComplate(e, item.selectOptions)"
              @select="
                e => selectAutoComplate(e, item.key, $index, item.selectOptions)
              "
            />
            <a-select
              v-if="item.operatorType === 'select'"
              v-model="record[item.key]"
              show-search
              :dropdown-style="dropdownStyle"
              :allow-clear="allowClear"
              style="width: 100%"
              :placeholder="item.placeholder || '请输入'"
              :disabled="item.disabled"
              @change="
                e => {
                  changeSelect(e, item.key, $index)
                }
              "
            >
              <a-select-option
                v-for="v in record[item.key + 'List'] || item.selectOptions"
                :key="v.value"
                :value="v.value"
                >{{ v.label }}</a-select-option
              >
            </a-select>
            <span v-if="item.operatorType === 'img'">
              <img
                v-if="typeof record[item.key] === 'string'"
                v-view-img
                class="table-img__comTable"
                :src="record[item.key]"
                alt=""
              />
              <img
                v-for="(img__, iii) in record[item.key] || []"
                v-else
                :key="iii"
                v-view-img
                class="table-img__comTable"
                :src="img__"
                alt=""
              />
            </span>
            <span
              v-if="!item.text && !item.operatorType"
              :class="[!item.event ? 'pointer-event' : 'pointer-cursor']"
              :style="{ color: item.setColor ? item.setColor(text) : '' }"
              @click="doOperator(record, text, item.title, $index)"
              >{{ item.statusOptions ? item.statusOptions[text] : text }}
            </span>
          </span>
          <span v-else>
            <span v-if="item.operatorType === 'img'">
              <img
                v-if="typeof record[item.key] === 'string'"
                v-view-img
                class="table-img__comTable"
                :src="record[item.key]"
                alt=""
              />
              <img
                v-for="(img__, iii) in record[item.key] || []"
                v-else
                :key="iii"
                v-view-img
                class="table-img__comTable"
                :src="img__"
                alt=""
              />
            </span>
            <span v-if="item.operatorType === 'img'">
              <img
                v-if="typeof record[item.key] === 'string'"
                v-view-img
                class="table-img__comTable"
                :src="record[item.key]"
                alt=""
              />
              <img
                v-for="(img__, iii) in record[item.key] || []"
                v-else
                :key="iii"
                v-view-img
                class="table-img__comTable"
                :src="img__"
                alt=""
              />
            </span>
            <span v-else>{{ text }}</span>
          </span>
        </span>
      </a-table>
    </div>
  </article>
</template>

<script>
import API from './../../api/proof'
import { cloneDeep } from 'lodash'
import TableSetting from './setting.vue'
export default {
  name: 'ColumnPage',
  components: { TableSetting },
  props: {
    fn: {
      type: [Boolean, Function],
      default: false
    },
    allowClear: {
      type: Boolean,
      default: true //
    },
    disabled: {
      type: Boolean,
      default: false // 只对input select 做🚫
    },
    y: {
      type: String,
      default: ''
    },
    x: {
      type: String,
      default: '100%'
    },
    formList: {
      type: Array,
      default: () => []
    },
    hasPage: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    url: {
      type: String,
      default: ''
    },
    defaultParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    rowSelectionEd: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default: () => []
    },
    settings: {
      type: Boolean,
      default: false
    },
    tableName: {
      type: String,
      default: 'defaultColumns'
    }
  },
  data() {
    return {
      selectedRows: [],
      tableSettingVisible: false,
      loading: false,
      dropdownStyle: {
        minWidth: 'max-content'
      },
      tabValue: '',
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ['25', '50', '100'],
        current: 1,
        pageSize: 25,
        total: 0
      },
      queryInfo: {},
      tableData: [],
      tableColumns: [],
      userInfo: {
        supplierId: localStorage.getItem('userId')
      },
      columnSetting: []
    }
  },
  computed: {
    colData() {
      return this.data
    },
    rowSelection() {
      return this.rowSelectionEd
        ? {
            onChange: (selectedRowKeys, selectedRows) => {
              this.selectedRows = selectedRowKeys
              this.$emit(
                'setSelectedRows',
                this.selectedRows,
                selectedRows,
                this.tableName
              )
            }
          }
        : null
    }
  },
  watch: {
    tableName(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.setColumns()
      }
    }
  },
  created() {
    this.setColumns()
  },
  mounted() {
    this.url && this.loadData()
  },
  methods: {
    open() {
      this.tableSettingVisible = true
    },
    closeTableSetting() {
      this.tableSettingVisible = false
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    blurAutoComplate(e, options) {
      console.log(e, options)
    },
    selectAutoComplate(e, key, index, options) {
      console.log(e, key, index)
      this.$emit('changeSelect', e, key, index)
    },
    changeSelect(e, key, index) {
      this.$emit('changeSelect', e, key, index)
    },
    blurInput(e, key, index) {
      this.$emit('blurInput', e, key, index)
    },
    changeInput(e, key, index) {
      this.$emit('changeInput', e, key, index)
    },
    setColumns() {
      if (this.columnSetting.length < 1) {
        const columnSetting = cloneDeep(this.columns)
        this.columnSetting = columnSetting
      }
      console.log('this', this.columns)
      this.tableColumns = cloneDeep(this.columns)
      const datas = JSON.parse(localStorage.getItem(this.tableName))
      const column = []
      if (datas?.length > 0) {
        const columns = cloneDeep(this.columns)
        datas?.forEach(value => {
          columns?.forEach(item => {
            if (value === item.title) {
              column.push(item)
            }
          })
        })
        this.tableColumns = column
      }
      this.tableColumns.forEach(_ => {
        _.dataIndex = _.key
        _.scopedSlots = { customRender: _.key }
        _.align = 'center'
      })
      console.log('data', this.columns)
    },
    async loadData() {
      const { current: pageNum, pageSize } = this.pagination
      const obj = { ...this.queryInfo, ...this.defaultParams, ...this.userInfo }
      this.hasPage && Object.assign(obj, { pageNum, pageSize })
      this.loading = true
      const result = await API.fetchData(this.url, obj)
      this.loading = false
      // this.fn &&  this.fn(result)
      this.tableData = result ? result.list || [] : []
      this.pagination.total = result.total || 0
    },
    handleTableChange(v) {
      this.pagination.current = v.current
      this.pagination.pageSize = v.pageSize
      this.loadData()
    },
    doOperator(record, text, title, index) {
      this.$emit('operator', record, text, title, index)
    }
  }
}
</script>

<style lang="less" scoped>
article {
  padding: 10px;
  background: #fff;
}
.pointer-event {
  pointer-events: none;
}
.pointer-cursor {
  cursor: pointer;
}
.hander-com-table {
  font-size: 16px;
  color: #000;
}
.hander-com-table:empty {
  display: none;
}
.table-img__comTable {
  max-width: 50px;
  max-height: 17px;
  margin-right: 8px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 3px;
  transition: all 1s;
  transform: scale(2);
}
</style>
